<?php

namespace app\facade;

use think\facade\Env;

class Yun
{
    private $captcha_id = '2d26bb132fd249f185c1755da619c5c4';
    private $secret_id = '2d22c1e9488b809b9e407ba88af35df0';
    private $secret_key = '2ec6a1e1f9f9f84b7db9493d40e5c484';

    public function verify($validate, $user)
    {
        $params = array();
        $params["captchaId"] = $this->captcha_id;
        $params["validate"] = $validate;
        $params["user"] = $user;
        // 公共参数
        $params["secretId"] = $this->secret_id;
        $params["version"] = 'v2';
        $params["timestamp"] = sprintf("%d", round(microtime(true) * 1000)); // time in milliseconds
        $params["nonce"] = sprintf("%d", rand()); // random int
        $params["signature"] = $this->sign($this->secret_key, $params);
        $result = $this->send_http_request($params);
        return $result;
    }

    /**
     * 计算参数签名
     * @param $secret_key 密钥对key
     * @param $params 请求参数
     */
    private function sign($secret_key, $params)
    {
        ksort($params); // 参数排序
        $buff = "";
        foreach ($params as $key => $value) {
            $buff .= $key;
            $buff .= $value;
        }
        $buff .= $secret_key;
        return md5(mb_convert_encoding($buff, "utf8", "auto"));
    }

    /**
     * 发送http请求
     * @param $params 请求参数
     */
    private function send_http_request($params)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://c.dun.163yun.com/api/v2/verify");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        /*
         * Returns TRUE on success or FALSE on failure. 
         * However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
         */
        $result = curl_exec($ch);
        // var_dump($result);

        if (curl_errno($ch)) {
            $msg = curl_error($ch);
            curl_close($ch);
            return array("error" => 500, "msg" => $msg, "result" => false);
        } else {
            curl_close($ch);
            return json_decode($result, true);
        }
    }
}
